﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Gueei.Gallery.Core.Services;

namespace Gueei.Gallery.Web.Controllers
{
    public class AdminFunctionController : Controller
    {
    	private delegate void ProcessReindex();

    	private ReindexService _reindexService;

		public AdminFunctionController(ReindexService reindexService)
		{
			_reindexService = reindexService;
		}

        public ActionResult Reindex()
        {
			if (reIndexWorking) return View();
			var processReindex = new ProcessReindex(DoReindex);
        	processReindex.BeginInvoke(new AsyncCallback(ReindexCompleted), processReindex);
        	return View();
        }

    	protected bool reIndexWorking
    	{
			get { return _reindexService.Progress < 100; }
    	}

    	private void DoReindex()
		{
			_reindexService.StartReindex();
		}

		[OutputCache(VaryByParam="*", Duration=100)]
		public ActionResult ReindexProgress()
		{
			return new JsonResult { Data = new {progress = _reindexService.Progress, message=_reindexService.Message}, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
		}

		public void ReindexCompleted(IAsyncResult result)
		{
		}
    }
}
